<template>
  <a-modal
    :visible="visible"
    okText="提交"
    :footer="false"
    cancelText="关闭"
    :title="title"
    :maskClosable="false"
    :destroyOnClose="true"
    :keyboard="false"
    width="1000px"
    @cancel="closeModal()">
    <div>

      <a-row>
        <a-col>
          <a-form layout="inline" :form="topForm">
            <a-form-item label="生成数量">
              <a-input-number
                v-model="topForm.exchangeAmount"
                :placeholder="maxNum ? '最多'+maxNum+'个' : '请输入生成数量'"
                :min="0"
                :max="maxNum ? maxNum : 999999"
                style="width: 180px;">
              </a-input-number>
            </a-form-item>
            <a-form-item label="">
              <a-button @click="produce" :loading="exchangeAmountLoading" type="primary">生成</a-button>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <search-table
        :url="url"
        ref="searchtable"
        :columns="columns"
        :form="form"
        :defaultParams="defaultParams"
        style="margin-top:20px;"
        >

        <template slot="searchForm">
          <a-form layout="inline"
                  :form="form">
            <a-form-item label="兑换码">
              <a-input v-decorator="['exchangeCode']"
                              placeholder="兑换码">
              </a-input>
              <a-input type="hidden" v-decorator="['couponId']" >
              </a-input>
            </a-form-item>

            <a-form-item label="兑换状态">
              <a-select style="width: 180px"
                        v-decorator="['exchangeStatus']"  
                        :options="exchangeStatus"></a-select>
            </a-form-item>
            <!-- <br>
            <a-form-item label="兑换时间">
              <fast-range-picker
                v-decorator="[
                'exchangeStartTime-exchangeEndTime',
              ]"
              >
              </fast-range-picker>
            </a-form-item>


            <a-form-item label="生成时间">
              <fast-range-picker
                v-decorator="[
                'createStartTime-createEndTime',
              ]"
              >
              </fast-range-picker>
            </a-form-item> -->
            <br>
            <br>
            <a-form-item>
              <a-button type="primary" class="searchBtn" @click="searchData">搜索</a-button>
            </a-form-item>

            <a-form-item>
              <a-button type="primary" class="searchBtn" @click="resertSearchData">重置</a-button>
            </a-form-item>

            <!-- <a-form-item label="">
              <a-button @click="deleteRows($refs.searchtable.selectedRowKeys)" type="primary">批量删除</a-button>
            </a-form-item> -->

            <a-form-item label="">
              <a-button @click="exports" type="primary">导出</a-button>
            </a-form-item>
            <!-- 
              :action="`http://192.168.0.153:8020/admin/coupon/exchange/import-excel`"
                :action="`${BASE_URL}/coupon/exchange/import-excel`" -->
            <a-form-item label="">
              <a-upload
                :multiple="false"
                :showUploadList="false"
                :beforeUpload="beforeUpload"
                :customRequest="customRequest">
                <a-button type="primary">导入</a-button>
              </a-upload>
            </a-form-item>
            <a-form-item label="">
              <!-- <a :href="moduleUrl" download="批量导入优惠券兑换码模板.xls" title="下载" target="_blank">点击下载模板</a> -->
              <a-button type="link" @click="downloadTemplate">下载模版</a-button>
            </a-form-item>

          </a-form>
        </template>


        <template slot="tableOperation" slot-scope="{ record }">
           <permission v-if="record.exchangeStatus == 0" authority="">
             <span class="text-danger pointer" @click="deleteRows([record.id])">删除</span>
           </permission>

        </template>
      </search-table>
    </div>
  </a-modal>
</template>
<script>
  import moment from "moment";
  import SearchTable from "./SearchTable";
  export default {
    name: 'dataModel',
    props: {
      record: {
        type: Object,
        default() {
          return {}
        }
      },
      visible: {
        type: Boolean,
        default: false
      },
    },
    computed: {
      title() {
        return '生成兑换码'
      },

    },
    components:{
      SearchTable
    },
    data() {
      return {
        fileList: [],
        url: '/coupon/exchange/page',
        moduleUrl: `${location.origin}/goldenhome/ghs/admin/coupon/exchange/template`,
        topForm: {
          couponId: '',
          exchangeAmount: undefined
        },
        exchangeAmountLoading: false, // 生成按钮等待
        form: this.$form.createForm(this, {name: 'table_search'}),
        columns: [
          {
            title: '兑换码',
            dataIndex: 'exchangeCode',
            key: 'exchangeCode',
            align: 'center',
          },
          {
            title: '生成时间',
            dataIndex: 'generateTime',
            key: 'generateTime'
          },
          {
            title: '兑换状态',
            dataIndex: 'exchangeStatus',
            key: 'exchangeStatus',
            align: 'center',
            customRender: (text)=>{
              let res = ''
              if(text==0){
                res = '未兑换'
              } else if(text==1){
                res = '已兑换'
              }
              return res;
            }
          },
          {
            title: '兑换时间',
            dataIndex: 'exchangeTime',
            key: 'exchangeTime',
          },
          {
            title: '兑换用户',
            dataIndex: 'exchangeUserName',
            key: 'exchangeUserName'
          },
          {
            title: '操作',
            dataIndex: 'operation',
            scopedSlots: {customRender: 'operation'}
          }
        ],
        exchangeStatus:[
          {
            label:'全部',
            value:''
          },{
            label:'已兑换',
            value:'1'
          },{
            label:'未兑换',
            value:'0'
          },
        ],
        defaultParams: {
          couponId: this.record.id
        },
        maxNum: 0
      }
    },
    watch: {
      visible(value) {
        this.maxNum = 0
        if (value && this.record.id) {
          this.defaultParams.couponId = this.record.id
          this.topForm.couponId = this.record.id
          this.topForm.exchangeAmount = undefined
          if(this.record.couponStocks != -1) {
            this.maxNum = Number(this.record.canGetExchangeAmount)
          }
        }
      }
    },
    created() {
      // this.accquireInitValue()
    },
    mounted() {},
    methods: {
      moment,
      searchData(){
        this.$refs.searchtable.handleSearch()
      },
      resertSearchData(){
        this.form.resetFields()
        this.searchData()
      },
      produce(){
        if(this.maxNum == 0 && this.record.couponStocks != -1) {
          this.$message.error('已达到最大生成数量')
          return false
        }
        if(!this.topForm.exchangeAmount){
          this.$message.error('请输入生成数量')
        } else {
          this.exchangeAmountLoading = true
          this.$post(
            '/coupon/exchange/add',
            this.topForm).then(res => {
            if (res && res.returnCode == 1000) {
              if(this.record.couponStocks != -1) {
                this.maxNum = this.maxNum - this.topForm.exchangeAmount
              }
              this.exchangeAmountLoading = false
              this.topForm.exchangeAmount = ''
              this.$message.success('生成成功')
              this.$refs.searchtable.refreshTable()
            } else {
              this.exchangeAmountLoading = false
              this.$message.success('生成失败')
            }
          })
          .catch(err => {
            this.exchangeAmountLoading = false
            this.$message.success('生成失败')
          })
        }
      },

      downloadTemplate(){
        this.$export('/coupon/exchange/template')
      },

      exports(){
        const params = this.$refs.searchtable.searchParams || {}
        this.$export(
          '/coupon/exchange/export-excel',
          params)
      },

      beforeUpload (file, fileList) {
        // console.log('file-----', file)
        // console.log('fileList-----', fileList)
        this.fileList = file
      },
      customRequest(){
        let form = new FormData()
        console.log(this.fileList)
        form.append('multipartFile', this.fileList);
        form.append('couponId', this.record.id);
        this.$post('/coupon/exchange/import-excel',form).then(res => {
          if (res && res.returnCode === 1000) {
            this.$message.success(res.message)
            this.$refs.searchtable.refreshTable()
          }
        })
      },

      deleteRows (ids) {
        let _this = this
        this.$confirm({
          title: '删除提示',
          content: '删除操作不可恢复，请确认是否删除？',
          okText: '确认删除',
          cancelText: '取消',
          onOk: ()=> {
            _this.$post(
              '/coupon/exchange/delete',
              ids).then(res => {
              if (res && res.returnCode == 1000) {
                this.maxNum = this.maxNum + 1
                _this.$message.success('删除成功')
                _this.$refs.searchtable.refreshTable()
              }
            })
          }
        })
      },
      closeModal(freshTable) {
        // this.form.resetFields()
        this.amountLoading = false
        this.$emit('cancel', true)
      },
    }
  }
</script>

<style scoped="scoped" lang="less">
  .middleSection{
    margin: 50px auto;
    width: 85%;
    height: 100px;
    background-color:	#F0F8FF;
    display: flex;
    /*justify-content: space-around;*/
    padding-top: 20px;
  }
  .bottomSection{
    margin: 50px auto;
    width: 85%;
    height: 100px;
    background-color:	#F0F8FF;
    display: flex;
    justify-content: space-around;
    padding-top: 20px;
  }
</style>